#!/usr/bin/python3
import os

from .Entity import Entity
from utils import My_Util2


class Mapper:
    """
    数据库操作接口
    """

    def __init__(self, context, entity: Entity) -> None:
        self.context = context
        self.entity: Entity = entity
        self.prefix: str = self.entity.table_name.split("_")[0].lower()
        self.my_util2 = My_Util2.My_Util(self.context)

    def code_includes(self):
        package = self.entity.package
        framework_package = f"""{self.context['package']}.{self.context['framework_package']}"""
        entity_name = self.entity.name
        includes = list()
        includes.append(f"""import com.baomidou.mybatisplus.core.mapper.BaseMapper;""")
        includes.append(f"""import {package}.{self.context["code_storage"]["root"]}.entity.{entity_name};""")
        includes = self.my_util2.sort_import_order(includes)
        return "\n".join(includes)

    def code(self):
        author = self.entity.author
        package = self.entity.package
        entity_name = self.entity.name
        comment = self.entity.comment
        prefix = self.prefix

        includes = self.code_includes()
        return f"""package {package}.{self.context["code_storage"]["root"]}.mapper;

{includes}

/**
 * <p>
 * {comment}操作接口
 * </p>
 *
 * @author {author}
 */
public interface {entity_name}Mapper extends BaseMapper<{entity_name}> {"{"}

{"}"}
"""

    def save_file(self, dir):
        _target_dir = os.path.join(dir, self.context["code_storage"]["root"], "mapper")
        if not os.path.exists(_target_dir):
            os.makedirs(_target_dir)
        with open(
            os.path.join(_target_dir, "{}Mapper.java".format(self.entity.name)),
            mode="w",
            encoding="utf-8",
        ) as f:
            f.write(self.code())
